<?php
namespace admin\action;

use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\core\Loader;

/**--tmpl-use--**/

class RoleAction extends CommonAction {

	public function C_start()
	{
		parent::C_start();	

		$this->assign('admin_manager_assoc_url','/admin/manager/getAdmin_manager');
		$this->assign('admin_node_assoc_url','/admin/node/getAdmin_node');

	}


	protected $serviceBean="admin.adminRole.service";


	public function getAdmin_role(HttpRequest $request) {
	
		/**--tmpl-indexbefore--**/
		$kw = $request->getParameter('kw');
		$request->addParameter('s_name',$kw);
		$this->index($request);
		/**--tmpl-indexafter--**/
		$items = $this->getTemplateVar('items');
		$total = $this->getTemplateVar('total');
		echo json_encode(array('items' => $items,'total' => $total));
		exit;
	
	
	}
	
	/**-- actionAdd --**/
	public function add(HttpRequest $request) {
	
		parent::add($request);
	
		$rbacService = Beans::get('admin.adminManager.service');
		/**--tmpl-addtodo--**/
		$availModule = $rbacService->getCurrentManagerAvailableModuleConfig();
		$this->assign('module_config',$availModule);
		$availNodes = $rbacService->getCurrentManagerAvailableNodes();
		$this->assign('nodes',$availNodes);
	
		$this->assign("title", "添加角色");
		$this->assign('bread', array('系统管理','角色列表',$this->getTemplateVar('title')));
		$this->assign('breadUrl',  array('javascript:;',url('admin/role/index'),'javascript:;'));

	}

	public function edit(HttpRequest $request) {

		parent::edit($request);
		$rbacService = Beans::get('admin.adminManager.service');
		$availModule = $rbacService->getCurrentManagerAvailableModuleConfig();
		$this->assign('module_config',$availModule);
		$availNodes = $rbacService->getCurrentManagerAvailableNodes();
		$this->assign('nodes',$availNodes);
		$adminRoleNodeModel = Loader::model('adminRoleNode');
		$roleNodes = $adminRoleNodeModel->getItems(array('role_id' => $request->getParameter('id')),array('node_id'));
		$roleNode_ids = array();
		foreach($roleNodes as $v){
			$roleNode_ids[] = $v['node_id'];
		}
		$this->assign('role_node_ids',$roleNode_ids);

		$this->assign("title", "编辑角色");
		$this->assign('bread', array('系统管理','角色列表',$this->getTemplateVar('title')));
		$this->assign('breadUrl',  array('javascript:;',url('admin/role/index'),'javascript:;'));
	}

	public function index(HttpRequest $request) {

        $this->page = $request->getParameter('page', 'intval');
        if ( $this->page <=0 ) {
            $this->page = 1;
        }

		$conditions = array();
		$s_name = $request->getParameter('s_name');
		$s_role_key = $request->getParameter('s_role_key');
		$s_remark = $request->getParameter('s_remark');
		$s_addtime = $request->getParameter('s_addtime');
		$s_edittime = $request->getParameter('s_edittime');
		$s_manager_id = $request->getParameter('s_manager_id');
		$s_del_status = $request->getParameter('s_del_status');
		$s_app_id = $request->getParameter('s_app_id');

		$s_s_addtime = $request->getParameter('s_s_addtime');
		$s_e_addtime = $request->getParameter('s_e_addtime');

		if($s_s_addtime !== '' && $s_s_addtime!== NULL){
			$conditions['addtime'] = array();
			$conditions['addtime']['>'] = $s_s_addtime.' 00:00:00';
		}

		if($s_e_addtime !== '' && $s_s_addtime!== NULL){
			if(!$conditions['addtime']){ $conditions['addtime'] = array();}
			$conditions['addtime']['<='] = $s_e_addtime.' 23:59:59';
		}

		if($s_name !== '' && $s_name!== NULL)$conditions['name'] = '%'.$s_name.'%';
		if($s_role_key !== '' && $s_role_key!== NULL)$conditions['role_key'] = '%'.$s_role_key.'%';
		if($s_remark !== '' && $s_remark!== NULL)$conditions['remark'] = '%'.$s_remark.'%';
		if($s_addtime !== '' && $s_addtime!== NULL)$conditions['addtime'] = '%'.$s_addtime.'%';
		if($s_edittime !== '' && $s_edittime!== NULL)$conditions['edittime'] = '%'.$s_edittime.'%';
		if($s_manager_id !== '' && $s_manager_id!== NULL)$conditions['manager_id'] = '%'.$s_manager_id.'%';
		if($s_del_status !== '' && $s_del_status!== NULL)$conditions['del_status'] = '%'.$s_del_status.'%';
		if($s_app_id !== '' && $s_app_id!== NULL)$conditions['app_id'] = '%'.$s_app_id.'%';

		$this->assign('_table','角色表');
		$this->assign('s_name',$s_name);
		$this->assign('s_role_key',$s_role_key);
		$this->assign('s_remark',$s_remark);
		$this->assign('s_addtime',$s_addtime);
		$this->assign('s_edittime',$s_edittime);
		$this->assign('s_s_addtime',$s_s_addtime);
		$this->assign('s_e_addtime',$s_e_addtime);
		$this->assign('s_manager_id',$s_manager_id);
		$this->assign('s_del_status',$s_del_status);
		$this->assign('s_app_id',$s_app_id);
		$this->assign('_filter',array('name','role_key','remark','addtime','edittime','admin_manager_id','del_status','app_id'));
		$this->assign('_header',array('','','','','','','','AppId'));


		//如果不是超级管理员，则只能看到自已添加的角色
		$myInfo = $this->getTemplateVar('myInfo');
		if($myInfo['role_id'] != 0){
			$conditions['manager_id'] = $myInfo['id'];
		}
		$this->setConditions($conditions);

		$pagesize = $request->getParameter('pagesize') ? $request->getParameter('pagesize') : $this->getPagesize();
		$order = $request->getParameter('order') ? $request->getParameter('order') : $this->getOrder();
		$order = str_replace('+' , " ",$order);
		$this->setPagesize($pagesize);
		$this->setOrder($order);
		$this->assign('order',$order);
		$this->assign('pagesize',$pagesize);
		//parent::index($request);
        if( $request -> getParameter('export') == 1 ){
            $this -> setPage(1);
            $this -> setPagesize(2147483648);
            $ids = $request->getParameter('ids');
            if( is_array($ids) ){
                $conditions['id']['$in']=$ids;
                $this -> setConditions($conditions);
            }
        }
		$this->order=array('edittime'=>-1);

		$service = Beans::get($this->getServiceBean());
        $total = $service->count($this->getConditions());
        $items = $service->getItems($this->getConditions(), $this->getFields(), $this->getOrder(),
            array($this->getPage(), $this->getPagesize()), $this->getGroup(), $this->getHaving());
        if( $request -> getParameter('export') == 1 ){
            $excel = array();
            foreach ($items as $k => $v) {
                $tmp = array();
                $tmp[] = $v["name"];
                $tmp[] = $v["remark"];
                $tmp[] = $v["addtime"];
                $tmp[] = $v["edittime"];
                $tmp[] = $v["status"]?"启用":"禁用";
                $tmp[] = $v["manager_name"];
                $excel[] = $tmp;
            }
            $header = array('角色名称', '角色描述', '添加时间', '修改时间', '账号状态', '操作人');
            phpexcel("角色列表", $header, $excel);
            exit();
        }
        $this->generatePageMenu($total);
        $this -> assign('page',$this->page);
        $this -> assign('items',$items);
		$this -> assign("title", "角色列表");
		$this -> assign('bread', array('系统管理',$this->getTemplateVar('title')));
		$this -> assign('breadUrl',  array('javascript:;','javascript:;'));
        $this->setView(strtolower($request->getAction()) . '/index');
	}
	
	public function do_add(HttpRequest $request)
	{
		$rbacService = Beans::get('admin.adminManager.service');
		$data = $request->getParameter('data');
		$myInfo = $this->getTemplateVar('myInfo');
		if($myInfo['role_id'] != 0){
			$data['manager_id'] = $myInfo['id'];
		}
		$nodes = $request->getParameter('node');
		$data['node'] = array_keys($nodes);

		if($data['node']==null){

			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'需最少选一种权限');

		}
		$availNodes = $rbacService->getCurrentManagerAvailableNodes();
		$availNode_ids = array();
		foreach($availNodes as $v){
			$availNode_ids[] = $v['id'];
		}
		//分配的权限大于自身权限
		if(!empty(array_diff($data['node'],$availNode_ids))){
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'非法操作');
		}
		$service = Beans::get($this->getServiceBean());
		
		if($service->count(array('name' => trim($data['name']))) >= 1)
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('ROLE_NAME_UNIQUE'));
		}
		$request->addParameter('data',$data);
		parent::do_add($request);	
	}
	
	public function do_edit(HttpRequest $request){
		$rbacService = Beans::get('admin.adminManager.service');
		$data = $request->getParameter('data');
		$nodes = $request->getParameter('node');

		$data['node'] = array_keys($nodes);

		if(!isset($data['status'])&&$data['node']==null){

			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'需最少选一种权限');

		}
		$availNodes = $rbacService->getCurrentManagerAvailableNodes();
		$availNode_ids = array();
		foreach($availNodes as $v){
			$availNode_ids[] = $v['id'];
		}
		//分配的权限大于自身权限
		if(!empty(array_diff($data['node'],$availNode_ids))){
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,'非法操作');
		}
		$service = Beans::get($this->getServiceBean());

        //查看角色下是否有管理员
		if($data['status']=='0'&&$service->isBelongSomeone(array($request->getParameter('id'))))
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('ROLE_IS_BELONG_SOMEONE'));
		}

		$data['manager_id'] = adminId();
	
		if(isset($data['name']) && $service->count(array('name' => trim($data['name']),'id' => array('!=' => $request->getParameter('id')))) >= 1)
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('ROLE_NAME_UNIQUE'));
		}
		$request->addParameter('data',$data);
		//exit;
		parent::do_edit($request);	
	}

	public function delete(HttpRequest $request)
	{
		$id = $request->getParameter('id');
		$service = Beans::get($this->getServiceBean());
		if($service->isBelongSomeone(array($id)))
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('ROLE_IS_BELONG_SOMEONE'));
		}
		
		parent::delete($request);
	}

	public function deletes(HttpRequest $request)
	{
		$ids = $request->getParameter('ids');
		$service = Beans::get($this->getServiceBean());
		if($service->isBelongSomeone($ids))
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('ROLE_IS_BELONG_SOMEONE'));
		}

		parent::deletes($request);
	}
	/**
	 * 禁用、启用多条数据
	 * @param HttpRequest $request
	 */
	public function do_updateStatus( HttpRequest $request ) {

		$ids = $request->getParameter('ids');
		$type = $request->getParameter('type');

		if ( empty($ids) ) AjaxResult::ajaxResult('error', COM_ERR_MSG);

		$service = Beans::get($this->getServiceBean());

		//查看角色下是否有管理员
		if($type=='0'&&$service->isBelongSomeone($ids))
		{
			AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,L('ROLE_IS_BELONG_SOMEONE'));
		}

		if($type==1){
			$bool=$service->updates(array('status'=>1),array('id' => array('$in' => $ids) ));

		}else{
			$bool=$service->updates(array('status'=>0),array('id' => array('$in' => $ids) ));

		}

		if ($bool ) {
			AjaxResult::ajaxSuccessResult();
		} else {
			AjaxResult::ajaxFailtureResult();
		}

	}
}
